<template>
  <view class="content">
    <view class="app-title ac">
      <view class="fl" @click="back">
        <image class="back" src="/static/img/back.png"></image>
      </view>
      应急信息
      <view class="history-icon" @click="goMaintenanceHistory">
        <u-icon name="clock" size="45"></u-icon>
      </view>
    </view>
    <view style="height: 155upx"></view>

    <view class="info-area">
      <view class="info-list">
        <view
          :class="['info-item', item.idK == selectItemID ? 'selected' : '']"
          v-if="emerList && emerList.length"
          v-for="(item, index) in emerList"
          :key="index"
          @click="selectEmer(item, index)"
        >
          <view class="item-header"> </view>
          <view class="item-body">
            <view class="body-top">
              <view>
                <u-icon name="warning-fill" color="#5396e7"></u-icon>
                <text>{{ item.faultTypeName }}</text>
                <u-icon
                  v-if="item.idK == selectItemID"
                  name="checkbox-mark"
                  color="#307BE0"
                ></u-icon>
                <text v-if="item.idK == selectItemID" style="color: #307be0"
                  >已选中</text
                >
                <text
                  style="position: absolute; right: 20px"
                  v-if="item.processCode > 0"
                  @click="openGroup(item)"
                  >查看群消息</text
                >
              </view>
              <view>
                <text>{{ item.lineName }}</text>
                <text>{{ item.staName }}</text>
                <text>{{ item.happenTime }}</text>
              </view>
              <view>{{ item.equName }}</view>
              <view>{{ item.content }}</view>
            </view>
            <hr />
            <view class="body-bottm">
              <view>
                <u-icon name="order"></u-icon>
                <text>接单</text>
                <text>{{ item.receiveCount }}</text>
                <u-icon name="account"></u-icon>
                <text>到场</text>
                <text>{{ item.arriveCount }}</text>
                <u-icon name="account"></u-icon>
                <text>参与应急</text>
                <text>{{ item.responseCount }}</text>
              </view>
              <u-steps
                :list="emergencyProcess"
                :current="
                  item.processCode > 1 ? item.processCode - 2 : item.processCode
                "
                mode="dot"
                active-color="#00aa47"
                un-active-color="#a2bdc6"
                class="emer-steps"
              ></u-steps>
            </view>
          </view>
        </view>
      </view>
      <view class="emer-tip">没有更多报警了~</view>
    </view>

    <view style="height: 100upx"></view>
    <view class="disposal-button" v-if="!param">
      <button
        @click="btn1 && receiveState ? orderRece(1) : ''"
        :class="[btn1 && receiveState ? 'active' : 'inactive']"
      >
        参与应急
      </button>
      <button @click="orderRece(2)" :class="[btn2 ? 'active' : 'inactive']">
        接单
      </button>
      <button @click="orderRece(3)" :class="[btn5 ? 'active' : 'inactive']">
        开始抢修
      </button>
      <button @click="goTroubleshoot()" :class="[btn3 ? 'active' : 'inactive']">
        应急处置
      </button>
      <button @click="initList()" :class="[btn4 ? 'active' : 'inactive']">
        刷新
      </button>
    </view>
    <view class="disposal-button disposal" v-else>
      <button
        @click="goTroubleshoot2()"
        :class="[selectedEmerCommuParam.faultId ? 'active' : 'inactive']"
      >
        查看进程
      </button>
    </view>
  </view>
</template>

<script>
import { WORK_CONTROLLER } from "../../../api/pms.js";
import { mapState } from "vuex";
export default {
  components: {},
  computed: {
    ...mapState(["wsEmerValue", "emerUpdataValue"]),
  },
  data() {
    return {
      btn1: false,
      btn2: false,
      btn3: false,
      btn4: true,
      btn5: false,
      presenceFlag: true,
      emerList: [],
      selectedEmerCommuParam: {},
      selectItemID: "",
      orderReceSucessID: "",
      emergencyProcess: [
        {
          name: "告警",
        },
        // {
        // 	name: '调度发布'
        // },
        {
          name: "指挥发布",
        },
        // {
        // 	name: '接警'
        // },
        {
          name: "派单",
        },
        {
          name: "接单",
        },
        {
          name: "抢修",
        },
        {
          name: "待审核",
        },
        {
          name: "故障修复",
        },
      ],
      param: "",
      faultId: "",
      receiveState: true,
      selectedItem: {},
    };
  },
  watch: {
    wsEmerValue: {
      handler(newVal, oldVal) {
        if (!this.orderReceSucessID) {
          this.resetButton();
          this.initList(false);
        } else {
          this.initList(false);
        }
      },
    },
    emerUpdataValue: {
      handler(newVal, oldVal) {
        if (!newVal && newVal != "delete") return;
        if (!this.orderReceSucessID) {
          this.resetButton();
          this.initList(false);
        } else {
          this.initList(false);
        }
      },
    },
  },
  onReachBottom() {},
  async created() {
    await this.initList();
    if (this.faultId) {
      let parseValue = JSON.parse(this.faultId);
      this.selectEmer({
        ...parseValue,
        idK: parseValue.faultId,
      });
    }
  },
  onBackPress(e) {
    this.back();
  },
  onLoad(options) {
    this.param = options.param;
    this.faultId = options.faultId;
  },

  methods: {
    openGroup(params) {
      console.log(params, "打开互动群");
      let chatgroupServer = this.$store.state.appServer.chatgroupServer;
      if (!chatgroupServer) {
        uni.showToast({
          title: "没有配置互动群服务器，请联系管理员",
          icon: "none",
        });
      }
      let obj = {
        username: this.$store.state.userInfo.tel,
        groupId: params.idK,
        contitle: `【${params.staName}】【${params.content}】应急群`,
        initPersons: "1,2,3",
      };
      let paths =
        `http://${chatgroupServer}/#/?password=66666` +
        "&username=" +
        obj.username +
        "&groupId=" +
        obj.groupId +
        "&contitle=" +
        obj.contitle +
        "&initPersons=" +
        obj.initPersons;
      this.$store.state.chatgroup = paths;

      uni.navigateTo({
        url: "/pages/emergency/chatgroup/chatgroup",
      });
    },
    back() {
      uni.redirectTo({
        url: "/pages/index/index",
      });
    },
    goMaintenanceHistory() {
      if (this.param) {
        uni.navigateTo({
          url:
            "/pages/emergency/historyList/index" +
            "?routefrom=" +
            "emerinfo" +
            "&param=process",
        });
      } else {
        uni.navigateTo({
          url:
            "/pages/emergency/historyList/index" + "?routefrom=" + "emerinfo",
        });
      }
    },

    // 接单，同时将工单状态流转
    async orderReceiving() {
      let woSn;
      let params = {
        emergencyId: this.selectItemID,
        pageNum: 1,
        pageSize: 10,
      };
      await this.fetch(
        "get",
        this.$store.state.baseUrl + WORK_CONTROLLER.GET_ALL_WORKORDER_LIST,
        params,
        true
      ).then((res) => {
        if (
          res.success &&
          res.data &&
          res.data.content &&
          res.data.content.length
        ) {
          woSn = res.data.content[0].woSn;
        } else {
          console.error(res);
        }
      });
      await this.fetch(
        "post",
        this.$store.state.baseUrl + `/api/work/task/receive`,
        {
          woSn: woSn,
        }
      ).then((res) => {});
    },
    //开始检修  将关联的工单流转
    async startCheck() {
      let woSn;
      let params = {
        emergencyId: this.selectItemID,
        pageNum: 1,
        pageSize: 10,
      };
      await this.fetch(
        "get",
        this.$store.state.baseUrl + WORK_CONTROLLER.GET_ALL_WORKORDER_LIST,
        params,
        true
      ).then((res) => {
        if (
          res.success &&
          res.data &&
          res.data.content &&
          res.data.content.length
        ) {
          woSn = res.data.content[0].woSn;
        } else {
          console.error(res);
        }
      });
      await this.fetch(
        "post",
        this.$store.state.baseUrl + WORK_CONTROLLER.POST_START,
        {
          woSn: woSn,
        },
        false
      ).then((res) => {});
    },
    orderRece(btn) {
      if (
        (btn == 2 && this.btn2) ||
        (btn == 1 && this.btn1) ||
        (this.btn5 && btn == 3)
      ) {
        if (this.selectItemID == "") return;

        let selectedItem;
        for (let i = 0; i < this.emerList.length; i++) {
          if (this.emerList[i].idK == this.selectItemID) {
            selectedItem = this.emerList[i];
          }
        }
        let contentJson = JSON.stringify([
          {
            name: this.$store.state.userInfo.name,
            id: this.getUserId(),
            phone: this.$store.state.userInfo.phone
              ? this.$store.state.userInfo.phone
              : this.$store.state.userInfo.tel,
            roleName: this.$store.state.userInfo?.roles?.[0].name,
          },
        ]);
        //  接单和 抢修  状态值改动
        let processCode = btn == 1 ? 3 : btn == 2 ? 5 : 6;

        let emergencyTPersonList =
          btn == 1
            ? [
                {
                  faultId: selectedItem.idK || "",
                  responseFlag: 1,
                  personId: this.getUserId(),
                  // contentJson
                },
              ]
            : [
                {
                  faultId: selectedItem.idK || "",
                  receiveFlag: 1,
                  personId: this.getUserId(),
                  // contentJson
                },
              ];

        let params = {
          processCode,
          faultId: selectedItem.idK || "",
          emergencyTPersonList,
          contentJson,
        };

        this.fetch(
          "PUT",
          this.$store.state.baseEmerUrl + "/emergency/faultAction",
          params,
          false
        ).then((res) => {
          if (res.success) {
            if (btn == 1) {
              uni.showToast({
                title: "参与应急成功！",
                icon: "none",
              });
            } else if (btn == 2) {
              uni.showToast({
                title: "接单成功！",
                icon: "none",
              });

              this.presenceFlag = true;
              this.sendPosition(selectedItem.idK);

              this.selectedEmerCommuParam = {
                faultId: selectedItem.idK,
                planOrderId: selectedItem.planOrderId || "",
                armcode: selectedItem.armcode || "",
                content: selectedItem.content,
              };

              this.btn3 = true;
              this.btn5 = true;

              this.orderReceSucessID = selectedItem.idK;

              this.$store.state.faultOrderInfoGlobal = {
                happenTime: selectedItem.happenTime,
                lineName: selectedItem.lineName,
                staName: selectedItem.staName,
                faultTypeName: selectedItem.faultTypeName,
              };
            } else if (btn == 3) {
              uni.showToast({
                title: "到场成功！",
                icon: "none",
              });
              this.presenceFlag = false;
            }
            this.initList(false);
          } else {
            if (res.message == "处理失败") {
              uni.showToast({
                title: res.message,
                icon: "none",
              });
            }
          }
        });

        // 调工单流转接单接口
        if (btn == 2) {
          this.orderReceiving();
        }
        // 调工单开始检修接口
        if (btn == 3) {
          this.startCheck();
        }
      }
    },
    goTroubleshoot() {
      if (this.btn3) {
        if (this.selectedEmerCommuParam) {
          let params = this.selectedEmerCommuParam;
          this.orderReceSucessID = "";
          uni.navigateTo({
            url:
              "/pages/emergency/troubleshoot/index" +
              "?params=" +
              JSON.stringify(params),
          });
        }
      }
    },
    goTroubleshoot2() {
      if (!this.selectedEmerCommuParam.faultId) return;
      if (this.selectedEmerCommuParam) {
        let params = this.selectedEmerCommuParam;
        this.orderReceSucessID = "";
        uni.navigateTo({
          url:
            "/pages/emergency/troubleshoot/index" +
            "?params=" +
            JSON.stringify(params) +
            "&param=process",
        });
        console.log("this.selectedEmerCommuParam", this.selectedEmerCommuParam);
      }
    },
    selectEmer(item) {
      console.log("ssss", item);
      this.selectItemID = item.idK;
      this.selectedEmerCommuParam = {
        faultId: item.idK,
        planOrderId: item.planOrderId || "",
        armcode: item.armcode || "",
        content: item.content,
        processCode: item.processCode,
        lineName: item.lineName,
        equName: item.equName,
        staName: item.staName,
        equTypeName: item.equTypeName,
      };

      this.confirmRoleData(item.idK);
      let code = this.selectedEmerCommuParam.processCode;
      code < 4 ? (this.receiveState = true) : (this.receiveState = false);
      this.selectedItem = item;
      // 应急状态是接单的话，发生位置信息
      if (item.processCode == 5) {
        this.presenceFlag = true;
        this.sendPosition(item.idK);
      } else {
        this.presenceFlag = false;
      }
    },
    resetButton() {
      this.btn1 = false;
      this.btn2 = false;
      this.btn3 = false;
      this.btn5 = false;
    },
    confirmRoleData(faultId) {
      let params = {
        personId: this.getUserId(),
        faultId,
      };
      this.fetch(
        "GET",
        this.$store.state.baseEmerUrl + "/emergency/faultPerson",
        params,
        false
      ).then((res) => {
        if (res.returnCode == "2004" && res.data) {
          this.btn1 = res.data.responseFlag ? false : true;
          this.btn2 =
            res.data.deliverFlag && !res.data.receiveFlag ? true : false;
          this.btn5 =
            res.data.arriveTime || !res.data.receiveFlag ? false : true;
          this.btn3 =
            res.data.receiveFlag && res.data.arriveTime ? true : false;
        } else {
          this.resetButton();
        }
      });
    },
    // 参与应急校验
    emergencyCheck() {},
    async initList(popup = true) {
      let params = {
        personId: this.getUserId(),
        lineId: "",
        level: "",
        type: 0,
        faultId: "",
      };
      await this.fetch(
        "GET",
        this.$store.state.baseEmerUrl + "/emergency/faultList",
        params,
        popup
      ).then((res) => {
        if (res.success && res.data) {
          this.emerList = res.data;
          for (let i = 0; i < this.emerList.length; i++) {
            this.emerList[i].happenTime = this.emerList[i].happenTime.substring(
              0,
              19
            );
          }
          if (this.selectItemID) {
            this.emerList.map((item, index) => {
              if (item.idK == this.selectItemID) {
                this.selectEmer(item);
              }
            });
          }
        } else {
          console.error(res);
        }
      });
    },
    sendPosition(faultId) {
      uni.getLocation({
        type: "gcj02",
        geocode: true, //获取城市具体地址
        success: (res) => {
          // console.log('当前位置的经度：' + res.longitude);
          // console.log('当前位置的纬度：' + res.latitude);
          let params = {
            personId: this.getUserId(),
            latitude: res.latitude,
            longitude: res.longitude,
            faultId,
          };
          this.fetch(
            "POST",
            this.$store.state.baseEmerUrl + "/emergency/emergencyLocation",
            params,
            false
          ).then((res) => {
            // if (res.success) {
            // console.log("定位数据发送成功！")
            // } else {
            // 	this.sendPosition()
            // }

            // if (uni.getStorageSync('port') != 8088) {
            // 到场成功后停止发送
            if (this.presenceFlag) {
              setTimeout(() => {
                this.sendPosition(faultId);
              }, 800);
            }
            // }
          });
        },
        fail: function (res) {
          console.error(res);
        },
      });
    },
  },
};
</script>

<style scoped lang="less">
.selected {
  // border: 2px solid #307BE0;
}

// /deep/.u-steps .u-steps__item {
// 	min-width: 88upx;
// }

/deep/.u-steps__item__text--row {
  span {
    font-size: 24upx;
  }
}

/deep/.u-steps__item:nth-child(1) {
  min-width: 50upx;
}

/deep/.u-steps__item:nth-child(4) {
  min-width: 50upx;
}

/deep/.u-steps__item:nth-child(5) {
  min-width: 40upx;
}

/deep/.u-steps__item:nth-child(6) {
  min-width: 40upx;
}

/deep/.u-steps__item:nth-child(7) {
  min-width: 50upx;
}

.app-title {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 99;

  .history-icon {
    float: right;

    /deep/.u-icon__icon {
      position: relative;
      top: 8upx !important;
    }
  }
}

.info-area {
  .info-list {
    width: 96%;
    margin: 0 auto;

    .info-item {
      box-shadow: -2upx -2upx 2upx rgba(0, 0, 0, 0.05),
        2upx 2upx 4upx rgba(0, 0, 0, 0.05);
      border-radius: 3upx;
      background: #e7f5ff;
      margin-bottom: 25upx;

      .item-header {
        width: 100%;
        height: 15upx;
        background-color: #b0d2ff;
        border-radius: 3upx 3upx 0 0;
      }

      .item-body {
        padding: 10upx;
        border-radius: 3upx;

        .body-top {
          margin-bottom: 24upx;

          view:nth-child(1) {
            margin-bottom: 10upx;

            text:nth-of-type(1) {
              font-weight: bold;
              padding-left: 6upx;
            }
          }

          view:nth-child(2) {
            position: relative;
            margin-bottom: 15upx;
            font-size: 25upx;

            text:nth-of-type(1) {
              margin-right: 35upx;
              font-weight: bold;
            }

            text:nth-of-type(2) {
              font-weight: bold;
            }

            text:nth-of-type(3) {
              position: absolute;
              right: 10upx;
              color: #81858e;
            }
          }

          view:nth-child(3) {
            font-size: 25upx;
            font-weight: bold;
            margin-bottom: 15rpx;
          }

          view:nth-child(4) {
            font-size: 25upx;
            color: #b2bbc2;
          }
        }

        hr {
          width: 90%;
          margin: 0 auto;
          border: 1px dashed #e0eefb;
        }

        .body-bottm {
          margin-top: 24upx;

          view:nth-child(1) {
            margin-bottom: 20upx;

            text:nth-of-type(2n-1) {
              color: #a5b1bd;
              padding-left: 10upx;
              padding-right: 14upx;
            }

            text:nth-of-type(2n) {
              margin-right: 54upx;
              color: #6d7b86;
            }
          }

          .emer-steps {
            margin-bottom: 30upx;
          }
        }
      }
    }
  }

  .emer-tip {
    margin-top: 40upx;
    text-align: center;
    color: #8a8a8a;
    // font-weight: 600;
    font-size: 34upx;
  }
}

.disposal-button {
  position: fixed;
  bottom: 0;
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
  background-color: skyblue;
  padding: 20upx 20upx 40upx;

  button {
    // width: 162upx;
    width: 122upx;
    color: black;
    font-size: 24upx;
    font-weight: bolder;
  }

  .active {
    background-color: #307be0;
  }

  .inactive {
    background-color: white;
  }
}

.disposal {
  justify-content: center;

  .button {
    width: 222upx;
  }
}
</style>
